package com.ichir.projects.uiflow;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ichir.projects.uiflow.events.IUiPartListener;
import com.ichir.projects.uiflow.ui.api.IUiView;

/**
 * Abstract {@link IUiView} implementation to handle listeners.
 * 
 * @author mahieddine
 * @since 1.0.0
 */
public abstract class AbstractUiView implements IUiView {

	/**
	 * View listeners.
	 */
	private List<IUiPartListener> listeners = new ArrayList<IUiPartListener>();

	/**
	 * Add an event listener.
	 * @param listener listener to add
	 */
	protected final void addHandledListener(IUiPartListener listener) {
		if (listeners.contains(listener)) {
			return;
		}
		listeners.add(listener);
	}

	/**
	 * Remove an event listener.
	 * @param listener listener to remove
	 */
	protected final void removeHandledListener(IUiPartListener listener) {
		if (! listeners.contains(listener)) {
			return;
		}
		listeners.remove(listener);
	}

	/**
	 * Fire an event.
	 * @param eventId event Id
	 */
	protected final void fireEvent(String eventId) {
		fireEvent(eventId, null);
	}

	/**
	 * Fire an event.
	 * @param eventId event Id
	 * @param attributes event attributes
	 */
	protected final void fireEvent(String eventId, Map<String, Object> attributes) {
		for (IUiPartListener listener : listeners) {
			listener.onEvent(this, eventId, attributes);
		}
	}
}
